//! Yaya安全服务层示例程序
//! 
//! 演示如何使用安全服务层的各种功能

use yaya_safe_services::prelude::*;
use log::{info, error};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    env_logger::init();
    
    info!("Yaya安全服务层示例程序启动");
    
    // 创建服务管理器
    let mut service_manager = ServiceManager::new()?;
    
    // 启动所有服务
    service_manager.start_all_services()?;
    
    // 演示各种服务功能
    demo_memory_service(&service_manager)?;
    demo_process_service(&service_manager)?;
    demo_filesystem_service(&service_manager)?;
    demo_network_service(&service_manager)?;
    demo_graphics_service(&service_manager)?;
    demo_desktop_environment(&service_manager)?;
    demo_shell_service(&service_manager)?;
    
    // 停止所有服务
    service_manager.stop_all_services()?;
    
    info!("示例程序运行完成");
    Ok(())
}

fn demo_memory_service(service_manager: &ServiceManager) -> Result<(), Box<dyn std::error::Error>> {
    info!("=== 内存服务演示 ===");
    
    let mem_service = service_manager.get_memory_service();
    let mut mem_guard = mem_service.lock().map_err(|e| format!("无法锁定内存服务: {}", e))?;
    
    // 分配内存
    let ptr1 = mem_guard.allocate(1024)?;
    info!("分配内存块1: 地址={}, 大小=1024 字节", ptr1);
    
    let ptr2 = mem_guard.allocate(2048)?;
    info!("分配内存块2: 地址={}, 大小=2048 字节", ptr2);
    
    // 写入内存
    let data = vec![1, 2, 3, 4, 5];
    mem_guard.write_memory(ptr1, &data)?;
    info!("写入内存: 地址={}, 数据大小={} 字节", ptr1, data.len());
    
    // 读取内存
    let read_data = mem_guard.read_memory(ptr1, data.len())?;
    info!("读取内存: 地址={}, 数据大小={} 字节", ptr1, read_data.len());
    
    // 获取内存状态
    let (used, free) = mem_guard.get_status();
    info!("内存状态: 已使用={} 字节, 空闲={} 字节", used, free);
    
    // 释放内存
    mem_guard.free(ptr1)?;
    info!("释放内存块1: 地址={}", ptr1);
    
    mem_guard.free(ptr2)?;
    info!("释放内存块2: 地址={}", ptr2);
    
    drop(mem_guard);
    info!("内存服务演示完成");
    Ok(())
}

fn demo_process_service(service_manager: &ServiceManager) -> Result<(), Box<dyn std::error::Error>> {
    info!("=== 进程服务演示 ===");
    
    let proc_service = service_manager.get_process_service();
    let mut proc_guard = proc_service.lock().map_err(|e| format!("无法锁定进程服务: {}", e))?;
    
    // 创建进程
    let pid1 = proc_guard.create_process("demo_process1", "echo 'Hello World'", 4096)?;
    info!("创建进程1: PID={}, 名称=demo_process1", pid1);
    
    let pid2 = proc_guard.create_process("demo_process2", "ls -la", 8192)?;
    info!("创建进程2: PID={}, 名称=demo_process2", pid2);
    
    // 获取进程信息
    let process_info = proc_guard.get_process_info(pid1)?;
    info!("进程信息: PID={}, 名称={}, 状态={:?}, 内存使用={} 字节", 
          process_info.pid, process_info.name, process_info.state, process_info.memory_usage);
    
    // 列出所有进程
    let processes = proc_guard.list_processes();
    info!("当前运行进程数量: {}", processes.len());
    for process in processes {
        info!("  - PID={}, 名称={}, 状态={:?}", 
              process.pid, process.name, process.state);
    }
    
    // 暂停和恢复进程
    proc_guard.pause_process(pid1)?;
    info!("暂停进程: PID={}", pid1);
    
    proc_guard.resume_process(pid1)?;
    info!("恢复进程: PID={}", pid1);
    
    // 终止进程
    proc_guard.terminate_process(pid1)?;
    info!("终止进程: PID={}", pid1);
    
    proc_guard.terminate_process(pid2)?;
    info!("终止进程: PID={}", pid2);
    
    drop(proc_guard);
    info!("进程服务演示完成");
    Ok(())
}

fn demo_filesystem_service(service_manager: &ServiceManager) -> Result<(), Box<dyn std::error::Error>> {
    info!("=== 文件系统服务演示 ===");
    
    let fs_service = service_manager.get_filesystem_service();
    let mut fs_guard = fs_service.lock().map_err(|e| format!("无法锁定文件系统服务: {}", e))?;
    
    // 创建目录
    fs_guard.create_directory("/home/user")?;
    info!("创建目录: /home/user");
    
    fs_guard.create_directory("/home/user/documents")?;
    info!("创建目录: /home/user/documents");
    
    // 创建文件
    fs_guard.create_file("/home/user/documents/test.txt")?;
    info!("创建文件: /home/user/documents/test.txt");
    
    // 写入文件
    let file_content = b"Hello, Yaya Safe Services! This is a test file.";
    fs_guard.write_file("/home/user/documents/test.txt", file_content)?;
    info!("写入文件: /home/user/documents/test.txt, 大小={} 字节", file_content.len());
    
    // 读取文件
    let read_content = fs_guard.read_file("/home/user/documents/test.txt")?;
    info!("读取文件: /home/user/documents/test.txt, 大小={} 字节", read_content.len());
    
    // 列出目录
    let dir_contents = fs_guard.list_directory("/home/user/documents")?;
    info!("目录内容: /home/user/documents");
    for (name, node_type, size) in dir_contents {
        info!("  - {} ({:?}, {} 字节)", name, node_type, size);
    }
    
    // 删除文件
    fs_guard.delete("/home/user/documents/test.txt")?;
    info!("删除文件: /home/user/documents/test.txt");
    
    drop(fs_guard);
    info!("文件系统服务演示完成");
    Ok(())
}

fn demo_network_service(service_manager: &ServiceManager) -> Result<(), Box<dyn std::error::Error>> {
    info!("=== 网络服务演示 ===");
    
    let net_service = service_manager.get_network_service();
    let mut net_guard = net_service.lock().map_err(|e| format!("无法锁定网络服务: {}", e))?;
    
    // 创建连接
    let conn_id = net_guard.create_connection(ConnectionType::TCP, "example.com", 80)?;
    info!("创建网络连接: ID={}, 类型=TCP, 远程地址=example.com:80", conn_id);
    
    // 发送数据
    let send_data = b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
    let sent_size = net_guard.send_data(conn_id, send_data)?;
    info!("发送数据: 连接ID={}, 大小={} 字节", conn_id, sent_size);
    
    // 接收数据
    let received_data = net_guard.receive_data(conn_id, 1024)?;
    info!("接收数据: 连接ID={}, 大小={} 字节", conn_id, received_data.len());
    
    // 获取连接信息
    let conn_info = net_guard.get_connection_info(conn_id)?;
    info!("连接信息: ID={}, 状态={:?}, 发送字节={}, 接收字节={}", 
          conn_info.id, conn_info.state, conn_info.sent_bytes, conn_info.received_bytes);
    
    // 列出所有连接
    let connections = net_guard.list_connections();
    info!("当前网络连接数量: {}", connections.len());
    
    // 关闭连接
    net_guard.close_connection(conn_id)?;
    info!("关闭网络连接: ID={}", conn_id);
    
    drop(net_guard);
    info!("网络服务演示完成");
    Ok(())
}

fn demo_graphics_service(service_manager: &ServiceManager) -> Result<(), Box<dyn std::error::Error>> {
    info!("=== 图形服务演示 ===");
    
    let gfx_service = service_manager.get_graphics_service();
    let mut gfx_guard = gfx_service.lock().map_err(|e| format!("无法锁定图形服务: {}", e))?;
    
    // 创建窗口
    let window_config = WindowConfig {
        title: "Yaya Demo Window".to_string(),
        width: 800,
        height: 600,
        resizable: true,
        fullscreen: false,
    };
    
    let window_id = gfx_guard.create_window(window_config)?;
    info!("创建窗口: ID={}, 标题='Yaya Demo Window', 尺寸=800x600", window_id);
    
    // 获取窗口配置
    let window_config = gfx_guard.get_window_config(window_id)?;
    info!("窗口配置: 标题='{}', 尺寸={}x{}, 可调整大小={}, 全屏={}", 
          window_config.title, window_config.width, window_config.height,
          window_config.resizable, window_config.fullscreen);
    
    // 调整窗口大小
    gfx_guard.resize_window(window_id, 1024, 768)?;
    info!("调整窗口大小: ID={}, 新尺寸=1024x768", window_id);
    
    // 清屏
    gfx_guard.clear_screen(window_id, 255, 255, 255, 255)?;
    info!("清屏操作: 窗口ID={}, 颜色=白色", window_id);
    
    // 获取显示模式
    let display_mode = gfx_guard.get_current_display_mode();
    info!("当前显示模式: {}x{} @ {}Hz, {} bpp", 
          display_mode.width, display_mode.height, 
          display_mode.refresh_rate, display_mode.bits_per_pixel);
    
    // 关闭窗口
    gfx_guard.close_window(window_id)?;
    info!("关闭窗口: ID={}", window_id);
    
    drop(gfx_guard);
    info!("图形服务演示完成");
    Ok(())
}

fn demo_desktop_environment(service_manager: &ServiceManager) -> Result<(), Box<dyn std::error::Error>> {
    info!("=== 桌面环境服务演示 ===");
    
    let de_service = service_manager.get_desktop_environment();
    let mut de_guard = de_service.lock().map_err(|e| format!("无法锁定桌面环境服务: {}", e))?;
    
    // 创建窗口
    let window_id1 = de_guard.create_window("Demo Window 1", 400, 300, WindowType::Normal)?;
    info!("创建窗口1: ID={}, 标题='Demo Window 1', 尺寸=400x300", window_id1);
    
    let window_id2 = de_guard.create_window("Demo Window 2", 500, 400, WindowType::Dialog)?;
    info!("创建窗口2: ID={}, 标题='Demo Window 2', 尺寸=500x400", window_id2);
    
    // 聚焦窗口
    de_guard.focus_window(window_id1)?;
    info!("聚焦窗口: ID={}", window_id1);
    
    // 移动窗口
    de_guard.move_window(window_id1, 100, 50)?;
    info!("移动窗口: ID={}, 新位置=(100, 50)", window_id1);
    
    // 调整窗口大小
    de_guard.resize_window(window_id1, 450, 350)?;
    info!("调整窗口大小: ID={}, 新尺寸=450x350", window_id1);
    
    // 设置壁纸
    de_guard.set_wallpaper("/usr/share/wallpapers/yaya.jpg")?;
    info!("设置壁纸: /usr/share/wallpapers/yaya.jpg");
    
    // 获取窗口列表
    let windows = de_guard.get_windows();
    info!("当前窗口数量: {}", windows.len());
    for window in windows {
        info!("  - ID={}, 标题='{}', 尺寸={}x{}, 位置=({}, {}), 聚焦={}", 
              window.id, window.title, window.width, window.height,
              window.x, window.y, window.focused);
    }
    
    // 关闭窗口
    de_guard.close_window(window_id1)?;
    info!("关闭窗口: ID={}", window_id1);
    
    de_guard.close_window(window_id2)?;
    info!("关闭窗口: ID={}", window_id2);
    
    drop(de_guard);
    info!("桌面环境服务演示完成");
    Ok(())
}

fn demo_shell_service(service_manager: &ServiceManager) -> Result<(), Box<dyn std::error::Error>> {
    info!("=== Shell服务演示 ===");
    
    let shell_service = service_manager.get_shell_service();
    let mut shell_guard = shell_service.lock().map_err(|e| format!("无法锁定Shell服务: {}", e))?;
    
    // 执行命令
    let (output, exit_code) = shell_guard.execute_command("ls", &["-la"])?;
    info!("执行命令: ls -la");
    info!("输出: {}", output);
    info!("退出码: {}", exit_code);
    
    // 改变目录
    shell_guard.change_directory("/home/user")?;
    info!("改变目录到: /home/user");
    
    // 获取当前目录
    let current_dir = shell_guard.get_current_directory();
    info!("当前目录: {}", current_dir);
    
    // 设置环境变量
    shell_guard.set_environment_variable("MY_VAR", "hello")?;
    info!("设置环境变量: MY_VAR=hello");
    
    // 获取环境变量
    if let Some(value) = shell_guard.get_environment_variable("MY_VAR") {
        info!("获取环境变量: MY_VAR={}", value);
    }
    
    // 执行更多命令
    let (output, exit_code) = shell_guard.execute_command("pwd", &[])?;
    info!("执行命令: pwd");
    info!("输出: {}", output);
    info!("退出码: {}", exit_code);
    
    let (output, exit_code) = shell_guard.execute_command("echo", &["Hello", "World"])?;
    info!("执行命令: echo Hello World");
    info!("输出: {}", output);
    info!("退出码: {}", exit_code);
    
    drop(shell_guard);
    info!("Shell服务演示完成");
    Ok(())
}